package com.spa.infrastructure.service.wx;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.spa.infrastructure.service.wx.config.ChatConfig;
import com.spa.infrastructure.service.wx.result.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class WXLoginService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ChatConfig chatConfig;

    /**
     * 网页授权通过code获取access_token snsapi_base式的网页授权流程即到此为止。
     *
     * @param code
     * @return
     */
    public AccessTokenResult getAccessToken(String code) {
        String url = Constant.ACCESS_TOKEN.replace("APPID", chatConfig.getAppid())
                .replace("SECRET", chatConfig.getSecret())
                .replace("CODE", code);
        String data = restTemplate.getForObject(url, String.class);
        return JSONUtil.toBean(data, AccessTokenResult.class);
    }

    /**
     * getPhoneNumber
     * 该接口用于将code换取用户手机号。 说明，每个code只能使用一次，code的有效期为5min。
     *
     * @param code
     * @param accessToken
     * @return
     */
    public PhoneNumberResult getPhoneNumber(String code,String accessToken) {
        String url = Constant.PHONE_NUMBER.replace("ACCESS_TOKEN", accessToken);
        // 手机号调用凭证
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("code", code);

        String data = restTemplate.postForObject(url, jsonObj,String.class);
        return JSONUtil.toBean(data, PhoneNumberResult.class);
    }

    /**
     * 通过refresh_token 刷新access_token
     *
     * @param refreshToken
     * @return
     */
    public RefreshAccessTokenResult refreshAccessToken(String refreshToken) {
        String url = Constant.REFRESH_TOKEN.replace("APPID", chatConfig.getAppid())
                .replace("REFRESH_TOKEN", refreshToken);
        String data = restTemplate.getForObject(url, String.class);
        return JSONUtil.toBean(data, RefreshAccessTokenResult.class);
    }

    /**
     * 拉去用户信息（scope为 snsapi_userinfo）
     *
     * @param accessToken
     * @param openId
     * @return
     */
    public UserInfoResult refreshAccessToken(String accessToken, String openId) {
        String url = Constant.USERINFO.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String data = restTemplate.getForObject(url, String.class);
        return JSONUtil.toBean(data, UserInfoResult.class);
    }

}
